package com.company.core.validator;


import com.alibaba.fastjson.JSON;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author lcl
 * @Title: ValidatorUtils
 * @ProjectName smart-planet
 * @Description: 数据校验工具类
 * @date 2018/10/12下午4:39
 */
public class ValidatorUtils {

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object  待校验对象
     * @param groups  待校验的组
     * @throws ValidationException 校验不通过，则报ValidationException异常
     */
    public static void validateEntity(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            Map<String,String> oMap = new HashMap<>();
            Iterator<ConstraintViolation<Object>> iterator =  constraintViolations.iterator();
            while (iterator.hasNext()){
                ConstraintViolation<Object> constraint = iterator.next();
                oMap.put(constraint.getPropertyPath().toString(),constraint.getMessage());
            }
            throw new ValidationException(JSON.toJSONString(oMap));
        }
    }
}
